<template>
	<view class="main" @click="emojiShow = false">
		<u-navbar :is-back="false">
			<view class="flex flex-jc-sb f1 flex-ai-c nav">
				<view class="nav-back" @click.stop="back">取消</view>
				<view style="text-align: center;">
					<view>写文章</view>
					<view>{{userinfo.username}}</view>
				</view>
				<view class="nav-send" @click.stop="send">{{ops.id?'发送':'发布'}}</view>
			</view>
		</u-navbar>
		<view class="content flex flex-dir-c flex-jc-sb flex-ai-c">
			<!-- 富文本 -->
			<editor show-img-toolbar id="editor" placeholder="分享动态..." @ready="onEditorReady"></editor>
			<!-- 转发类容 -->
			<view v-if="ops.type == 1" class="flex" style="width: 100%;">
				<view>
					<video style="width: 200rpx;height: 200rpx;" :src="chatUser.video" show-fullscreen-btn
						object-fit="contain"></video>
				</view>
				<view style="margin-left: 20rpx;">
					<view>@{{chatUser.username}}</view>
					<rich-text class="rich" :nodes="chatUser.content"></rich-text>
				</view>
			</view>
			<view v-if="ops.type == 2" class="flex" style="width: 100%;">
				<view>
					<video style="width: 200rpx;height: 200rpx;" :src="chatUser.list[0].video" show-fullscreen-btn
						object-fit="contain"></video>
				</view>
				<view style="margin-left: 20rpx;">
					<view>@{{chatUser.list[0].username}}</view>
					<rich-text class="rich" :nodes="chatUser.list[0].content"></rich-text>
				</view>
			</view>
			<view class="type">
				<view>
					<text style="margin-right: 40rpx;">类型(必填)</text>
					<u-radio-group v-model="gather.value" :disabled="chatUser.typeid?true:false">
						<u-radio v-for="(item) in gather.navList" :key="item.id" :name="item.id">
							{{item.text}}
						</u-radio>
					</u-radio-group>
				</view>
				<view class="flex flex-ai-c">
					<text style="margin-right: 10rpx;">标题</text>
					<u-input placeholder="请填写标题" v-model="gather.title"></u-input>
				</view>
				<!-- <view>分类</view> -->
			</view>
			<!-- 相册 -->
			<view class="bottom" style="position: relative;">
				<view class="photo flex flex-wrap-w flex-jc-c" v-show="video.length">
					<view v-for="(item,index) in video" :key="index" class="photo-img">
						<view class="close" @click.stop="delPir(index)">
							<u-icon name="close" size="24rpx" color="#fff"></u-icon>
						</view>
						<video v-if="!status" :src="item" show-fullscreen-btn object-fit="contain"></video>
						<video v-else :src="item" show-fullscreen-btn object-fit="contain"></video>
					</view>
				</view>
				<view class="edit flex flex-jc-sa">
					<u-icon name="photo" size="50" @click="chooseImg"></u-icon>
					<view style="font-size: 50rpx;">@</view>
					<view style="font-size: 50rpx;" @click.stop="open(2)">#</view>
					<view @click.stop="open(3)" class="flex flex-ai-c">
						<view class="bq bci"></view>
					</view>
					<u-icon @click.stop="undo" name="close-circle" size="48"></u-icon>
					<u-icon name="plus-circle" size="50"></u-icon>
				</view>
			</view>
			<view class="pop" v-if="emojiShow" style="width: 100%;">
				<emoji @change="onEmoji" />
			</view>
			<!-- 词条搜索 closeable-->
			<u-popup v-model="entryShow" mode="bottom" height="70%">
				<view class="u-wrap">
					<view class="u-search-box">
						<view class="u-search-inner">
							<u-search class="u-search-text" @search="getEntryList" @change="onEntrySearch"
								placeholder="根据词条名搜索" search-icon="search" :show-action="false"
								v-model="entry.searchValue"></u-search>
						</view>
					</view>
					<view class="u-menu-wrap">
						<scroll-view scroll-y scroll-with-animation class="u-tab-view menu-scroll-view"
							:scroll-top="entry.scrollTop">
							<view v-for="(item,index) in entry.entryTypeList" :key="item.id" class="u-tab-item"
								:class="[entry.current == item.id ? 'u-tab-item-active' : '']" :data-current="item.id"
								@tap.stop="swichMenu(index,item)">
								<text class="u-line-1">{{item.text}}</text>
							</view>
						</scroll-view>
						<view style="width: 0;" class="f1">
							<template v-if="!entry.entryList.length">
								<view class="thumb-box flex flex-wrap-w" @click.stop="changeEntyy(0)">
									<image class="item-menu-image" src="" mode=""></image>
									<view class="item-menu-name f1" style="width: 0;">
										<text class="description">
											没有该词条，点击创建词条
										</text>
									</view>
								</view>
							</template>
							<block v-for="item in entry.entryList" :key="item.id">
								<scroll-view scroll-y class="right-box" v-if="entry.current == item.type"
									style="margin-bottom: 20rpx;">

									<view class="thumb-box flex flex-wrap-w" @click.stop="changeEntyy(item)">
										<image class="item-menu-image" :src="item.img" mode=""></image>
										<view class="item-menu-name f1" style="width: 0;">
											<text class="description">
												#{{item.title}}#
											</text>
										</view>
									</view>
								</scroll-view>
							</block>
						</view>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script setup lang="ts">
	import {
		ref,
		inject,
		reactive
	} from 'vue'
	import {
		onLoad,
		onUnload
	} from '@dcloudio/uni-app'
	import {
		useStore
	} from 'vuex'
	import article from '@/api/article';
	import common from '@/api/common.js'
	import emoji from '@/components/emoji.vue'
	interface userObj {
		[propName : string] : any
	}
	const apiTry : Function = inject('$try')
	let editorCtx : any = ref()
	let ops : any = ref({})
	let video : any = ref([])
	let userinfo = uni.getStorageSync('userinfo')
	const status = ref(false)
	let emojiShow = ref(false)//表情弹窗
	let chatUser = ref()
	let entryShow = ref(false)//词条弹窗
	let gather = reactive({
		navList: [],
		value: null,
		title: ''
	})
	let entry = reactive({
		scrollTop: 0, //tab标题的滚动条位置
		current: 0, // 预设当前项的值
		menuHeight: 0, // 左边菜单的高度
		menuItemHeight: 0, // 左边菜单item的高度
		searchValue: '',
		entryList: [],
		entryTypeList: [],
		entryAddList: []
	})
	const store = useStore()
	const msgAlert : Function = inject('$msgAlert')

	// 词条相关
	const onEntrySearch = (v : string) => {
		if (!v) return getEntryList()
	}
	// entry.current
	const onEditorReady = () => {
		uni.createSelectorQuery().select('#editor').context((res : any) => {
			editorCtx.value = res.context
		}).exec()
	}
	const chooseImg = () => {
		uni.chooseVideo({
			sourceType: ['camera', 'album'],
			success: (res) => {
				video.value = [res.tempFilePath]
				status.value = true
			}
		});
	}
	const changeEntyy = (obj : any) => {
		let title = obj ? obj.title : entry.searchValue
		if (!title.trim()) return uni.showToast({
			title: '请输入词条',
			icon: 'none'
		})
		let info = {
			title: title,
			type: entry.current,
			img: ''
		}
		entry.entryAddList = [...entry.entryAddList, info]
		editorCtx.value.insertText({
			text: `#${title}#`,
		})

		entryShow.value = false
	}
	const dictionary = async () => {
		const res = await common.dictionary('entry')
		entry.entryTypeList = res.data.entry
		res.data.entry.unshift({
			id: 0,
			text: '未分类',
			type: 'qt'
		})
		getEntryList()
	}
	const getEntryList = async () => {
		const res = await article.getEntryList({
			page: 1,
			pageSize: 50,
			searchValue: entry.searchValue,
			type: entry.current
		})
		entry.entryList = res.data
	}
	const swichMenu = async (index : number, item : userObj) => {
		if (item.id == entry.current) return
		entry.current = item.id
		getEntryList()
		if (entry.menuHeight == 0 || entry.menuItemHeight == 0) {
			getElRect('menu-scroll-view', 'menuHeight')
			getElRect('u-tab-item', 'menuItemHeight')
		}
		entry.scrollTop = index * entry.menuItemHeight + entry.menuItemHeight / 2 - entry.menuHeight / 2
	}
	const getElRect = (elClass : string, dataVal : string) => {
		uni.createSelectorQuery().select("." + elClass).fields(({ size: true }), (res : any) => {
			if (!res) {
				setTimeout(() => {
					getElRect(elClass, null);
				}, 10);
				return;
			}
			entry[dataVal] = res.height


		}).exec()

	}

	const onEmoji = (item : String) => {
		editorCtx.value.insertText({
			text: item
		})
	}
	//按钮事件
	const open = (i : number) : void => {
		switch (i) {
			case 1:
				break
			case 2:
				entryShow.value = !entryShow.value
				break
			case 3:
				emojiShow.value = !emojiShow.value
				break
		}
	}
	//获取分类
	const getType = async () => {
		const [err, res] = await apiTry(common.dictionary('writeArticle'))
		if (err) return
		gather.navList = res.data.writeArticle
		gather.value = gather.navList[0].id
	}
	//撤销
	const undo = () => {
		editorCtx.value.undo()
	}
	const delPir = (index : number) => {
		video.value.splice(index, 1)
	}

	//编辑
	const edit = () => { //编辑：文章id
		editorCtx.value.getContents({
			success: async (data : any) => {
				let text = reg(data.text)
				let ids = []
				if (text.length) {
					let newList = merge(text, entry.entryAddList)
					for (let i in newList) {
						await createEntry(newList[i].title, (entryid : number) => {
							if (entryid) {
								ids.push(entryid)
							}
						}, newList[i].type)
					}

				}
				const [err, res] = await apiTry(article.updataArticle({
					id: ops.value.id,
					content: data.html,
					entryid: ids.length ? ids.join(',') : ''
				}))
				if (err) return
				if (res.status !== 200) return
				if (status.value) {
					upload()
				}
			}
		})
	}
	//发送
	const send = () => {
		if (!gather.value) return msgAlert('请选择类型')
		if (!video.value.length && !chatUser.value.video) return msgAlert('请选择视频')
		if (ops.value.id) return edit()
		add()
	}
	const upload = () => {
		uni.uploadFile({
			// @ts-ignore
			url: `${uni.$baseUrl}/uploadVideo`,
			name: 'file',
			filePath: video.value[0],
			header: {
				"Authorization": uni.getStorageSync('token')
			},
			formData: {
				id: ops.value.id
			},
			success: (() => {
				// let data = JSON.parse(res.data)
				uni.navigateBack({
					success: () => {
						status.value = false
						msgAlert('发布成功')
					}
				})
			})
		})
	}
	const reg = (str : any = '') => {
		str = str.match(/\#(.+?)\#/g)
		let title = []
		for (let i in str) {
			str[i].trim()
			let re = str[i].match(/#(.*?)#/)
			title.push(re[1])
		}
		return title
	}
	const createEntry = async (title : string, cb : Function, type = 0) => {
		const res = await article.createEntry({
			title: title,
			type: type
		})

		cb(res.data)
	}
	const merge = (arr : AnyArray, arr2 : AnyArray) => {
		const newArr = arr.map(item => {
			const data = arr2.find(i => item == i.title)
			return {
				item,
				...data
			}
		})

		return newArr
	}
	//新增
	const add = () => {
		editorCtx.value.getContents({
			success: async (data : any) => {
				let text = reg(data.text)
				let ids = []
				if (text.length) {
					let newList = merge(text, entry.entryAddList)
					for (let i in newList) {
						await createEntry(newList[i].title, (entryid : number) => {
							if (entryid) {
								ids.push(entryid)
							}
						}, newList[i].type)
					}

				}
				// chatUser.value.typeid
				const [err, res] = await apiTry(article.addArticle({
					content: data.html,
					typeid: 3,
					entryid: ids.length ? ids.join(',') : '',
					title: gather.title,
					forwardid: chatUser.value.id ? chatUser.value.id : null
				}))
				if (err) return
				if (res.status !== 200) return
				ops.value.id = res.data
				//转发新增
				if (ops.value.type == 1) {
					uni.navigateBack({
						success: () => {
							status.value = false
							msgAlert('发布成功')
						}
					})
					return
				}
				upload()
			}
		})
	}

	//卸载监听
	onUnload(() => {
		uni.$off('update')
		editorCtx.value = null
		store.commit('chatUser', {})
	})
	onLoad((op) => {
		op.type = op.type || 0
		getType()
		ops.value = op
		chatUser.value = store.state.chatUser
		
		if (chatUser.value.typeid) {
			gather.value = 12
		}
		if (op.video !== 'null') {
			if (op.video) {
				video.value = [op.video]
			}
		}
		uni.$on('update', (res) => {
			editorCtx.value.setContents({
				html: res.content
			})
		})
		dictionary()
	})
	const back = () => {
		uni.navigateBack()
	}
</script>

<style src="./index.scss"></style>